
import React, {
  Component,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  TextInput,
  ListView,
  Image,
  Picker,
  DatePickerIOS
} from 'react-native';

global.simuEventsList = [];
var ChildMap = {};
var PickerItem = Picker.Item;
var PopOption = require('./PopOption');
var Title =require('./Title');
var query = require('./Query').query;
var ENTER_ARROW = require('../../icon/enter-arrow.png');
class SimuEvent extends Component{

  constructor(props){
    super(props);

    this.props.childList.forEach((item, index, array) =>{
            ChildMap[item.name] = item;
        })

    this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
        child:this.props.childList[0] === undefined ? '' : this.props.childList[0].name,
        event:'入校',
        time:new Date(),
        timeZoneOffsetInHours: (-1) * (new Date()).getTimezoneOffset() / 60,
        showOption:'none',
        modalVisible:false,
        dataSource:this.ds.cloneWithRows(simuEventsList),
      };
  }


  _onPressReturn(){
    this.props.navigator.pop();
  }

  _onPressSend(){
    if(this.state.child === '' || this.state.event === '' || this.state.time === null){
      return;
    }
    this.setState({showOption:'confirm'});
    this.setState({modalVisible:true});
  }

  _onPressConfirmSend(){
    simuEventsList.push({child:this.state.child,event:this.state.event,time:this.state.time});
    this.setState({dataSource:this.ds.cloneWithRows(simuEventsList)});
    this.setState({modalVisible: false});

    var type = this.state.event === '入校' ? 0 : 1;
    query.submitEvent(ChildMap[this.state.child].bbId,
                      this.state.time.Format("yyyy-MM-dd hh:mm"),
                      type,
                      this,
                      function(owner,response){
                        if(response.success === true){
                          console.log('成功提交模拟事件.');
                        }});

    console.log('发送模拟事件给服务器:'+this.state.child+'/' + ChildMap[this.state.child].bbId);
  }

  _onPressClearBtn(){
    if(this.state.child === '')
    {
      return;
    }

    query.clearEvent(ChildMap[this.state.child].bbId,
                      new Date().Format("yyyy-MM-dd"),
                      this,
                      function(owner,response){
                        if(response.success === true){
                          var tmpEvents = [].concat(simuEventsList);
                          simuEventsList = [];
                          tmpEvents.forEach((item, index, array) =>{
                            if(item.child != owner.state.child){
                              simuEventsList.push(item);
                            }
                          })
                          owner.setState({dataSource:owner.ds.cloneWithRows(simuEventsList)});
                          console.log('成功清除模拟事件.');
                        }});
    console.log('发送清除模拟事件给服务器:'+this.state.child+'/' + ChildMap[this.state.child].bbId);
  }

  _onDateChange(date){
    console.log("设置事件发生时间:"+date.toLocaleString());
    this.setState({time: date});
  }

  _showSendOpt(){
    return(
      <View style={{marginLeft:10,marginRight:10}}>
        <TouchableOpacity style={{height:100,borderRadius:10,backgroundColor:'#FFF'}} onPress={this._onPressConfirmSend.bind(this)}>
          <Text style={{color:'#656565',fontSize:12,marginTop:15,textAlign:'center'}}>确定要发送模拟数据到服务器?</Text>
          <View style={{borderStyle:'solid',borderWidth:1,borderColor:'#eeeeee',marginTop:15}}/>
          <Text style={{color:'#06a9fe',fontSize:20,marginTop:20,textAlign:'center'}}>确定</Text>
        </TouchableOpacity>

        <TouchableOpacity style={{height:60,borderRadius:10,backgroundColor:'#FFF',marginTop:8,marginBottom:10}} onPress={()=>{this.setState({modalVisible: false})}}>
          <Text style={{color:'#06a9fe',fontSize:20,marginTop:20,textAlign:'center'}}>取消</Text>
        </TouchableOpacity>

      </View>
    )
  }

  _showChildPicker(){
    var pickerItems = [];
    this.props.childList.forEach((item, index, array) =>{
            pickerItems[index] =  <PickerItem
                                    key = {index}
                                    value={item.name}
                                    label={item.name}
                                  />
        })

    return(
        <Picker
          selectedValue={this.state.child}
          mode={"dropdown"}
          onValueChange={(value) => this.setState({child: value})}
          style={{marginTop:5,height:250,backgroundColor:'#FFF'}}>
          {pickerItems}
        </Picker>
      )
  }

  _showEventPicker(){
    return(
        <Picker
          selectedValue={this.state.event}
          mode={"dropdown"}
          onValueChange={(value) => this.setState({event: value})}
          style={{marginTop:5,height:250,backgroundColor:'#FFF'}}>
          <PickerItem
            value={"入校"}
            label={"入校"}
          />
          <PickerItem
            value={"出校"}
            label={"出校"}
          />
        </Picker>
      )
    
  }

  _showTimePicker(){
    return(
        <DatePickerIOS
          style={{marginTop:5,height:250,backgroundColor:'#FFF'}}
          date={this.state.time===null?new Date():this.state.time}
          mode="time"
          minuteInterval={1}
          timeZoneOffsetInMinutes={this.state.timeZoneOffsetInHours * 60}
          onDateChange={this._onDateChange.bind(this)}
        />
      )
  }

  _dateTextTip(date){
    if(date === null) {
      return("");
    }
    else{
      return date.Format("yyyy-MM-dd hh:mm");
    }

  }

  _onPressChooseChild(){
    this.setState({modalVisible:true});
    this.setState({showOption:'showChild'});
  }

  _onPressChooseEvent(){
    this.setState({modalVisible:true});
    this.setState({showOption:'showEvent'});
  }

  _onPressChooseTime(){
    this.setState({modalVisible:true});
    this.setState({showOption:'showTime'});
  }



  _renderRecord(rowData: string,sectionID: number, rowID: number){
    return (
        <View style={styles.listRow}>
          <Text style={{fontSize:12,color:'red'}}>{rowData.child}</Text>
          <Text style={{fontSize:12,color:'red'}}>{rowData.event}</Text>
          <Text style={{fontSize:12,color:'red'}}>{this._dateTextTip(rowData.time)}</Text>
        </View>
    )
  }

  render(){

    var popOption = null;
    if(this.state.showOption==='showChild' && this.state.modalVisible){
      popOption = 
              <PopOption renderOptions={this._showChildPicker.bind(this)}
                visible = {this.state.modalVisible} 
                onClose={()=>{this.setState({modalVisible:false})}}/>;
    }
    else if(this.state.showOption === 'showEvent' && this.state.modalVisible){
      popOption = 
              <PopOption renderOptions={this._showEventPicker.bind(this)}
                visible = {this.state.modalVisible} 
                onClose={()=>{this.setState({modalVisible:false})}}/>;
    }
    else if(this.state.showOption === 'showTime' && this.state.modalVisible){
      popOption = 
              <PopOption renderOptions={this._showTimePicker.bind(this)}
                visible = {this.state.modalVisible} 
                onClose={()=>{this.setState({modalVisible:false})}}/>;
    }
    else if(this.state.showOption === 'confirm' && this.state.modalVisible){
      popOption = 
              <PopOption renderOptions={this._showSendOpt.bind(this)}
                visible = {this.state.modalVisible} 
                onClose={()=>{this.setState({modalVisible:false})}}/>;
    }

    return(
      <View style={styles.container}>
        
        {popOption}

        <Title title={{left:"返回",center:"模拟事件",right:'发送',
              leftAct:this._onPressReturn.bind(this),rightAct:this._onPressSend.bind(this)}}></Title>

        <View style={styles.innerContainer}>

          <View style={[styles.flowRight,styles.bottomLine]}>
            <Text style={styles.text}>选择孩子:</Text>
            <TouchableOpacity style={styles.optionButton} onPress={this._onPressChooseChild.bind(this)}>
              <Text style={styles.optionButtonText}>{this.state.child}</Text>
              <Image style={styles.enterIcon} source={ENTER_ARROW} />
            </TouchableOpacity>
          </View>

          <View style={[styles.flowRight,styles.bottomLine]}>
            <Text style={styles.text}>选择事件:</Text>
            <TouchableOpacity style={styles.optionButton} onPress={this._onPressChooseEvent.bind(this)}>
              <Text style={styles.optionButtonText}>{this.state.event}</Text>
              <Image style={styles.enterIcon} source={ENTER_ARROW} />
            </TouchableOpacity>
          </View>

           <View style={[styles.flowRight,styles.bottomLine]}>
             <Text style={styles.text}>选择时间:</Text>
             <TouchableOpacity style={styles.optionButton} onPress={this._onPressChooseTime.bind(this)}>
                <Text style={styles.optionButtonText}>{this._dateTextTip(this.state.time)}</Text>
                <Image style={styles.enterIcon} source={ENTER_ARROW} />
              </TouchableOpacity>
            </View>
       </View> 

       <Text style={{fontSize:16,color:'red',marginTop:20,marginLeft:10}}>已发送事件列表：</Text>
       <ListView dataSource={this.state.dataSource}
                  renderRow={this._renderRecord.bind(this)}
                  enableEmptySections={true}
                style={styles.listView} />

      <TouchableOpacity style={styles.clearButton} onPress={this._onPressClearBtn.bind(this)}>
        <Text style={styles.clearButtonText}>清空当日模拟事件</Text>
      </TouchableOpacity>

      </View>


    )

  }
}

/**
 * 定义本模块的样式表
 * @type {*|{type, property}|{panHandlers}|Object|{duration, create, update}|Config}
 */
const styles = StyleSheet.create({
  container: {
    backgroundColor: '#eeeeee',
    flex: 1,
  },
  listView: {
    backgroundColor: '#eee',
    marginTop:10,
  },
  listRow:{
    flexDirection:'row',
    alignSelf:'stretch',
    flex: 1,
    height:30,
    backgroundColor: 'white',
    padding: 10,
    alignItems:'center',
    justifyContent:'space-around',
    borderStyle:'solid',
    borderColor:'#eeeeee',
    borderWidth:0.5,
  },
  innerContainer:{
    backgroundColor: '#FFF',
  },
  flowRight:{ //账号、密码、登录
    height:50,
    flexDirection: 'row', //水平排布
    alignItems: 'center', //中心线对齐
    marginLeft:20,
    marginRight:20,
  },
  bottomLine:{
    borderBottomWidth:1,
    borderBottomColor:'#eeeeee',
  },
  
  text:{
    flex:1,
    fontSize:16,
    color:'#04679b',
  },
  optionButton:{
    flex:3,
    flexDirection:'row',
    justifyContent:'space-between',
    alignItems:'center',
    alignSelf:'stretch',
  },
  optionButtonText:{
    fontSize:14,
    color:'#04679b',
    textAlign:'center',
  },
  enterIcon: {
    marginRight:10,
  },
  clearButton:{
    height:40,
    alignSelf:'center',
    backgroundColor:'#FFF',
    borderRadius:6,
    borderStyle:'solid',
    borderWidth:1,
    borderColor:'#06a9fe',
    justifyContent:'center', 
    marginTop:15,
    marginBottom:30,
  },
  clearButtonText:{
    fontSize:16,
    textAlign:'center', //内容水平方向居中
    color:'#06a9fe'
  },
})

module.exports = SimuEvent;
